//
//  OAuthViewController.m
//  MyMicroBlog
//
//  Created by Apple on 16/9/22.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "OAuthViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "SVProgressHUD.h"
#import "HMNetworkTools.h"

@interface OAuthViewController () <UIWebViewDelegate>
@property(strong,nonatomic)UIWebView *webV;
@end

@implementation OAuthViewController

//懒加载视图
-(UIWebView *)webV{
    _webV = [[UIWebView alloc]init];
    return _webV;
}

//重写loadView方法
-(void)loadView{
    self.view = self.webV;
    //解决底部黑条
    self.webV.opaque = NO;
    //网页代理
    self.webV.delegate = self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestLogin];
    [self setupNaviUI];
}

//第三方登录请求
-(void)requestLogin{
    NSString *url = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",WeiBoAppKey,WeiBoRedirect_URI];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [_webV loadRequest:request];
}

//设置导航栏
-(void)setupNaviUI{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTitle:@"取消" andImageName:nil andTarget:self andAction:@selector(cancleAction)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:@"自动登录" andImageName:nil andTarget:self andAction:@selector(loginAction)];
}

//点击事件
-(void)cancleAction{
    //删除菊花
    [SVProgressHUD dismiss];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

-(void)loginAction{
    [_webV stringByEvaluatingJavaScriptFromString:@"document.getElementById('userId').value = '18271432322';document.getElementById('passwd').value = 'qingdesky523441@'"];
}

//网页代理
//开始加载
-(void)webViewDidStartLoad:(UIWebView *)webView{
    //加载菊花
    [SVProgressHUD show];
}

//加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //移除菊花
    [SVProgressHUD dismiss];
}

//加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}

//将要加载请求
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //截取字符串,判断合法
    NSURL *url = request.URL;
    if (![url.absoluteString hasPrefix:@"code="]) {
        //不是需要的地址
        return YES;
    }
    if ([url.query hasPrefix:@"code="]) {
        //截取字符串
        NSRange range = [url.query rangeOfString:@"code="];
        NSString *code = [url.query substringFromIndex:range.location];
        //通过code获取accessToken
       
    }
    return YES;
}
@end
